/**
 * 
 */
package com.my.test.testnet;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * create date: 2010-10-21 下午03:40:42
 * @author Angela Tao
 * @version 1.0
 *
 */
public class TalkServer implements Runnable{
	
	private ServerSocket ss;
	private Socket s;
	private DataInputStream dis;
	private DataOutputStream dos;

	/**
	 * 
	 */
	public TalkServer() {
		// TODO Auto-generated constructor stub
	}
	
	public void connect(){
		try {
			ss = new ServerSocket(4433);
			s = ss.accept();
			
			dis = new DataInputStream(s.getInputStream());
			dos = new DataOutputStream(s.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void listen(){
		try {
			//System.out.println("Client: "+dis.readUTF());
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String info =  br.readLine();
			while(!"bye".equals(info)){
				dos.writeUTF(info);
				dos.flush();
				System.out.println("Server: "+info);
				//System.out.println("Client: "+dis.readUTF());
				
				info = br.readLine();
			}
			br.close();
			dis.close();
			dos.close();
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TalkServer ts = new TalkServer();
		ts.connect();
		new Thread(ts).start();
		ts.listen();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while(true){
				System.out.println("Client: "+dis.readUTF());
			}		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
